from typing import List, Dict, Any, Optional
from qwen3_agent_function_calling.tools.Tool import Tool

class CalculatorTool(Tool):
    """计算器工具"""

    def get_name(self) -> str:
        return "calculator"

    def get_description(self) -> str:
        return "用于执行数学计算，需传入数学表达式参数"

    def get_parameters(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "expression": {
                    "type": "string",
                    "description": "数学表达式，支持+、-、*、/、()运算",
                    "examples": ["2+3*4", "(5+8)/2", "100-50"]
                }
            },
            "required": ["expression"],
        }

    def execute(self, arguments: Dict[str, Any]) -> str:
        try:
            expression = arguments.get("expression", "").strip()
            if not expression:
                return "错误：请提供数学表达式（如'2+3*4'）"

            # 安全检查
            allowed_chars = set("0123456789+-*/(). ")
            if not all(c in allowed_chars for c in expression):
                return "错误：表达式只能包含数字和基本运算符(+、-、*、/、.、())"

            result = eval(expression)
            return f"计算结果：{expression} = {result}"
        except Exception as e:
            return f"计算错误：{str(e)}"
